import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:intl/intl.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/domain/widgets/image_upload.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/global_easy_loading.dart';
import 'package:flutter_syt/routes.all.dart';
import 'package:flutter_syt/theme/font_styles.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/image_picker_helper.dart';
import 'package:flutter_syt/utils/utils_dlog.dart';
import 'package:url_launcher/url_launcher_string.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

@RoutePage(name: "feedbackPage")
class FeedbackPage extends StatefulWidget {
  final int id;

  const FeedbackPage(this.id);
  // const FeedbackPage();
  @override
  _FeedbackPageState createState() => _FeedbackPageState();
}

class _FeedbackPageState extends State<FeedbackPage> {
  late TextEditingController textController = new TextEditingController();
  int? module;
  String? subModule;
  int? type;
  // Map<String, dynamic> dataSource = {};
  List dataSources = [];
  List<File> images = [];
  bool isZh = false;
  String _title = '';
  String _inputTitle = '';
  List _feedbackModule = [];
  Map? _module;
  List _sysTemBatch = [];
  String? _titile;
  // int count = 0;
  Future _save() async {
    List<String> urls = [];
    // count = 0;
    Future uploadImage(int index) async {
      var item = images[index];
      try {
        var result = await API.shared.common.uploadImage(item.path);
        urls.add(result.url);
      } catch (e) {}
      index++;
      if (index < images.length) {
        await uploadImage(index);
      }
    }

    if (images.isNotEmpty) {
      await uploadImage(0);
    }

    // for (var item in images) {
    //   var result = await API.shared.common.uploadImage(item.path);
    //   urls.add(result.url);
    // }
    await API.shared.feedback.add(
        module: module,
        subModule: subModule,
        type: type,
        text: textController.text,
        images: urls,
        moduleId: _module?['id']);
  }

  _submit() async {
    // 因屏蔽了功能模块选项，所以默认为1。
    if (module == null) {
      module = 1;
    }
    if (subModule == null) {
      subModule = "1";
    }
    if (module == null) {
      customShowToast('请选择反馈模块');
      return;
    }
    if (module == 1 && subModule == null) {
      customShowToast(S.of(context).choose_function);
      return;
    }
    // if (type == null) {
    //   customShowToast(S.of(context).choose_type);
    //   return;
    // }
    if (textController.text == '') {
      customShowToast(S.of(context).enter_feedback);
      return;
    }
    await loading(_save, text: S.of(context).submitting);
    customShowSuccess(S.of(context).submitted);
    Navigator.of(context).pop();
  }

  Future getSysTemBatch() async {
    var list = await API.shared.common.getSysTemBatch(
        keys: ['feedback_setting', 'feedback_scene_copywriting']);
    if (list is List) {
      _sysTemBatch = list;
    }
    _sysTemBatch.forEach((element) {
      if (element['key'] == 'feedback_scene_copywriting') {
        var local = appContext.storage.getString("storyLocal") ??
            Intl.getCurrentLocale();
        Map map = jsonDecode(element['value']);
        if (local.contains('zh')) {
          _titile = map['zh'];
        } else {
          _titile = map['en'];
        }
      }
    });
    checkDataSource();
  }

  checkDataSource() {
    dataSources.clear();
    _sysTemBatch.forEach((element) {
      if (element['relevance_id'] == _module?['id']) {
        List rows = jsonDecode(element['value']);

        rows.forEach((element) {
          if (element['key'] == 'fb_title') {
            _title = isZh ? element['value']['zh'] : element['value']['en'];
          } else if (element['key'] == 'fb_input') {
            _inputTitle =
                isZh ? element['value']['zh'] : element['value']['en'];
          }
          if (element['key'] == 'fb_online_service' ||
              element['key'] == 'fb_hotline' ||
              element['key'] == 'fb_email') {
            dataSources.add(element);
          }
        });
      }
    });
    if (mounted) {
      setState(() {});
    }
  }

  // getSystemSetting() async {
  //   var json = await API.shared.common.getSystemSetting('feedback_setting');
  //   List rows = jsonDecode(json['value']);

  //   rows.forEach((element) {
  //     if (element['key'] == 'fb_title') {
  //       _title = isZh ? element['value']['zh'] : element['value']['en'];
  //     } else if (element['key'] == 'fb_input') {
  //       _inputTitle = isZh ? element['value']['zh'] : element['value']['en'];
  //     }
  //     if (element['key'] == 'fb_online_service' ||
  //         element['key'] == 'fb_hotline' ||
  //         element['key'] == 'fb_email') {
  //       dataSources.add(element);
  //     }
  //   });
  //   if (mounted) {
  //     setState(() {});
  //   }
  // }

  Future getFeedbackModule() async {
    _feedbackModule = await API.shared.feedback.feedbackModule();
    DLog(_feedbackModule);
    _feedbackModule.forEach((element) {
      if (element['id'] == _module?['id']) {
        _module = element;
      }
    });
    if (mounted) {
      setState(() {});
    }
  }

  String? encodeQueryParameters(Map<String, String> params) {
    return params.entries
        .map((MapEntry<String, String> e) =>
            '${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}')
        .join('&');
  }
  // await loading(getFeedbackModule);

  @override
  void initState() {
    super.initState();
    var local =
        appContext.storage.getString("storyLocal") ?? Intl.getCurrentLocale();
    isZh = local.contains('zh');
    // if (widget.title != null) {
    _module = {'id': widget.id, "title": ''};
    // }
    getSysTemBatch();
    getFeedbackModule();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    textController.dispose();
  }

  String getIcon(String key) {
    // if (element['key'] == 'fb_online_service') {
    //     dataSource[element['key']] = element['value'];
    //     dataSource[element['key']]['im'] =
    //         'assets/icons/icon_online_service.png';
    //   } else if (element['key'] == 'fb_hotline') {
    //     dataSource[element['key']] = element['value'];
    //     dataSource[element['key']]['im'] =
    //         'assets/icons/icon_reserve_hotline.png';
    //   } else if (element['key'] == 'fb_email') {
    //     dataSource[element['key']] = element['value'];
    //     dataSource[element['key']]['im'] =
    //         'assets/icons/icon_email_feedback.png';
    //   } else if (element['key'] == 'fb_title') {
    //     _title = isZh ? element['value']['zh'] : element['value']['en'];
    //   } else if (element['key'] == 'fb_input') {
    //     _inputTitle = isZh ? element['value']['zh'] : element['value']['en'];
    //   }
    String icon = '';
    switch (key) {
      case 'fb_online_service':
        icon = 'assets/icons/icon_online_service.png';
        break;
      case 'fb_hotline':
        icon = 'assets/icons/icon_reserve_hotline.png';
        break;
      case 'fb_email':
        icon = 'assets/icons/icon_email_feedback.png';
        break;
      default:
    }
    return icon;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      // resizeToAvoidBottomInset: false,
      appBar: AppBar(
        title: Text(
          S.of(context).feedback_title,
          style: FontStyles.headerTextStyle_18.copyWith(
            fontWeight: FontWeight.w500,
          ),
        ),
        actions: [
          Container(
            margin: EdgeInsets.only(right: 15.0),
            child: TextButton(
              style: TextButton.styleFrom(padding: EdgeInsets.all(0)),
              child: Text(
                S.of(context).feedback_history,
                style: FontStyles.headerTextStyle_16.copyWith(
                  color: ThemeColor.colorBlack60,
                  // fontWeight: FontWeight.w500,
                ),
              ),
              onPressed: ClickUtils.debounce(() {
                RouteManager.push(context, RoutMapping.feedbackListPage());
              }),
            ),
          ),
        ],
      ),
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: ClickUtils.debounce(() {
          // 触摸收起键盘
          FocusScope.of(context).requestFocus(FocusNode());
        }),
        child: Stack(
          children: [
            Container(
              padding: EdgeInsets.only(bottom: 90, top: 10),
              child: ListView(
                children: [
                  Visibility(
                      visible: _feedbackModule.length > 1,
                      child: Container(
                        margin:
                            EdgeInsets.only(bottom: 10, left: 15, right: 15),
                        child: Row(
                          children: [
                            Text(
                              S.current.scene +
                                  ((_module ?? {})
                                          .keys
                                          .toList()
                                          .contains('title')
                                      ? _module!['title']
                                      : ''),
                              style: FontStyles.headerTextStyle_16.copyWith(
                                color: ThemeColor.colorBlack80,
                                // fontWeight: FontWeight.w500,
                              ),
                            ),
                            SizedBox(
                              width: 20,
                            ),
                            Visibility(
                                visible: _feedbackModule.length > 1,
                                child: GestureDetector(
                                  onTap: () async {
                                    var result =
                                        await DialogHelper.showFeedbackBottom(
                                      context, _feedbackModule,
                                      title: _titile,
                                      //     (value) {
                                      //   DLog(value);
                                      //   _module = value;
                                      //   checkDataSource();
                                      // }
                                    );
                                    if (result is Map) {
                                      _module = result;
                                      checkDataSource();
                                    }
                                  },
                                  child: Text(
                                    S().switch_scene,
                                    style:
                                        FontStyles.headerTextStyle_16.copyWith(
                                      color: ThemeColor.colorBlack80,
                                      // fontWeight: FontWeight.w500,
                                    ),
                                  ),
                                )),
                          ],
                        ),
                      )),

                  Visibility(
                      visible: dataSources.isNotEmpty,
                      child: Container(
                        padding: EdgeInsets.symmetric(horizontal: 15),
                        child: Column(
                          children: [
                            Container(
                              margin: EdgeInsets.only(bottom: 10),
                              alignment: Alignment.topLeft,
                              child: Text(
                                _title.replaceAll('\\n', '\n'),
                                style: FontStyles.headerTextStyle_18.copyWith(
                                  color: ThemeColor.colorBlack80,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            ),
                            Container(
                              height: 1,
                              color: Color(0xffEFEFEF),
                            ),

                            ...dataSources.map((e) {
                              Map item = e['value'];
                              return GestureDetector(
                                onTap: () async {
                                  // launchUrlString("mailto:707656@qq.com");
                                  // officialmedia@2021chengdu.com
                                  if (e['key'] == 'fb_online_service') {
                                    RouteManager.push(context,
                                        RoutMapping.service_socket('self'));
                                  } else if (e['key'] == 'fb_hotline') {
                                    launchUrlString("tel:${item['value']}");
                                  } else if (e['key'] == 'fb_email') {
                                    await launchUrlString(
                                        "mailto:${item['value']}");
                                  }
                                },
                                child: Container(
                                    // color: Colors.red,
                                    margin: EdgeInsets.only(
                                      top: 10,
                                    ),
                                    child: Column(
                                      children: [
                                        Row(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Image.asset(
                                              getIcon(e['key']),
                                              width: 20,
                                            ),
                                            SizedBox(
                                              width: 10,
                                            ),
                                            //  Expanded(child: Text('casdlfjasldjflasjdflaksjdflk;ajsdkfnvzdksjfvajksdnfvdnszfkjnsvdjk')),
                                            Expanded(
                                                child: Text(
                                              // ""
                                              // '翻译及帮助热线：0086-28-6167 0808 \n（中、英、法、西、俄）',
                                              (isZh ? item['zh'] : item['en'])
                                                  .replaceAll('\\n', '\n'),
                                              style: FontStyles
                                                  .headerTextStyle_16
                                                  .copyWith(
                                                color: ThemeColor.colorBlack80,
                                                fontWeight: FontWeight.w500,
                                              ),
                                            )),
                                          ],
                                        ),
                                        SizedBox(
                                          height: 10,
                                        ),
                                        Container(
                                          height: 1,
                                          color: Color(0xffEFEFEF),
                                        )
                                      ],
                                    )),
                              );
                            }).toList(),
                            // FeedbackSelect(
                            //   FeedbackSelectEntity.create(
                            //     '请选择模块及功能',
                            //     [
                            //       FeedbackOptionEntity.create('首页',
                            //           'assets/icons/icon_tab_active_home.png', 1),
                            //       FeedbackOptionEntity.create('赛事',
                            //           'assets/icons/icon_tab_active_games.png', 2),
                            //       FeedbackOptionEntity.create('资讯',
                            //           'assets/icons/icon_tab_active_news.png', 3),
                            //       FeedbackOptionEntity.create('个人中心',
                            //           'assets/icons/icon_tab_active_mine.png', 4),
                            //     ],
                            //   ),
                            //   onChange: (int value) {
                            //     setState(() {
                            //       module = value;
                            //     });
                            //   },
                            // ),
                            // CategoryDropdownButton(
                            //   show: module == 1,
                            //   title: '功能',
                            //   onChanged: (String? value) {
                            //     subModule = value;
                            //   },
                            // ),
                            // FeedbackSelect(
                            //   FeedbackSelectEntity.create(
                            //     S.of(context).choose_type,
                            //     [
                            //       FeedbackOptionEntity.create(
                            //           S.of(context).abnormal_function,
                            //           'assets/icons/icon_feedback_consult@2x.png',
                            //           1),
                            //       FeedbackOptionEntity.create(
                            //           S.of(context).proposal,
                            //           'assets/icons/icon_feedback_advice@2x.png',
                            //           2),
                            //     ],
                            //   ),
                            //   onChange: (int value) {
                            //     type = value;
                            //   },
                            // ),
                          ],
                        ),
                      )),
                  // Container(
                  //   width: double.infinity,
                  //   height: 10.0,
                  //   color: ThemeColor.bkColorF8F8F8,
                  // ),
                  Container(
                    margin: EdgeInsets.only(top: 10),
                    padding: EdgeInsets.symmetric(horizontal: 15),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Image.asset(
                              'assets/icons/icon_feedback_title.png',
                              width: 20,
                            ),
                            SizedBox(
                              width: 10,
                            ),
                            Expanded(
                              child: Text(
                                _inputTitle.isNotEmpty
                                    ? _inputTitle
                                    : S.of(context).feedback_hint,
                                style: FontStyles.headerTextStyle_16.copyWith(
                                  color: ThemeColor.colorBlack80,
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            )
                          ],
                        ),
                        // Container(
                        //   alignment: Alignment.topLeft,
                        //   // margin: EdgeInsets.only(top: 15.0, bottom: 0.0),
                        //   child:
                        // ),
                        Container(
                          margin: EdgeInsets.symmetric(vertical: 0.0),
                          // color: Colors.red,
                          child: TextField(
                            inputFormatters: [
                              FilteringTextInputFormatter.deny(
                                  appContext.emojiRegexp)
                            ],
                            // enableInteractiveSelection: true,
                            controller: textController,
                            keyboardType: TextInputType.multiline,
                            maxLines: 5,
                            maxLength: 3000,
                            autofocus: false,
                            decoration: InputDecoration(
                              border: InputBorder.none,
                              hintText: S.of(context).feedback_hint2,
                              counterText: '',
                              hintStyle: TextStyle(
                                color: ThemeColor.colorBlack20,
                                fontSize: 16,
                              ),
                            ),
                          ),
                        ),
                        Row(
                          children: [
                            Container(
                              alignment: Alignment.topLeft,
                              // margin: EdgeInsets.symmetric(vertical: 15.0),
                              child: ImageUpload(
                                maxLength: 3,
                                width: 95,
                                height: 95,
                                images: images,
                                onChange: (newImages) {
                                  // if (mounted) {
                                    setState(() {
                                      images = newImages;
                                    });
                                  // }
                                },
                              ),
                            ),
                          ],
                        ),
                        Padding(
                          padding: EdgeInsets.only(top: 12),
                          child: Row(
                            children: [
                              Text(
                                S.of(context).optional_photos,
                                style: FontStyles.headerTextStyle_12.copyWith(
                                  color: ThemeColor.colorBlack40,
                                ),
                              ),
                            ],
                          ),
                        )
                      ],
                    ),
                  ),
                ],
              ),
            ),
            Positioned(
              bottom: 20,
              left: 0,
              right: 0,
              child: Container(
                margin: EdgeInsets.fromLTRB(0, 20.0, 0, 0.0),
                padding: EdgeInsets.symmetric(horizontal: 15.0, vertical: 6.0),
                decoration: BoxDecoration(
                  border: Border(
                    top: BorderSide(
                      color: ThemeColor.dividerColor_grey,
                      width: 0.5,
                      style: BorderStyle.solid,
                    ),
                  ),
                ),
                child: ElevatedButton(
                    child: Text(
                      S.of(context).give_feedback,
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                    onPressed: ClickUtils.debounce(
                      () {
                        _submit();
                      },
                    )),
              ),
            )
          ],
        ),
      ),
    );
  }
}
